package util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class Utilities {

    public static HashMap<String, String> getEnvironmentVariables() {
        Map<String, String> map = System.getenv();
        HashMap<String, String> env = new HashMap<>();

        for (String k : map.keySet()) {
            env.put(k, map.get(k));
        }

        return env;
    }

    public static String getTempDirectoryPath() throws IOException {
        File temp = File.createTempFile("temp", ".tmp");
        String absolutePath = temp.getAbsolutePath();

        return absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
    }

    public static String getDesktopDirectoryPath() {
        try {
            Process process = Runtime.getRuntime().exec("reg query \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\" /v DESKTOP");
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            StringBuilder sb = new StringBuilder("");
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            int p = sb.indexOf("REG_SZ");

            if (p == -1) {
                return null;
            }

            return sb.substring(p + "REG_SZ".length()).trim();
        } catch (IOException ex) {
            return null;
        }
    }
    
    public static String getUserDirectoryPath() {
        return System.getProperty("user.home");
    }

    public static String getSystemDirectoryPath() {
        return System.getenv("SystemRoot");
    }

    public static String getExternalIP() throws MalformedURLException, IOException {
        return new BufferedReader(new InputStreamReader(new URL("http://agentgatech.appspot.com").openStream())).readLine();
    }

}
